package com.lib.TrapDoor;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.lib.index.indexBuildTool;
import com.lib.index.indexEncrypted;
import com.lib.model.encryptedIndex;

import Jama.Matrix;



public class EncryptedTroopHelper {
	/**
	 * 获取v个[0,2v)之间不同的随机数
	 * @param v
	 * @return
	 */
	public static List<Integer>getRandom(int v)
	{
		Random random=new Random();
		int tempRandom=0;
		int u=4*v;
		List<Integer>list=new ArrayList<Integer>();
		boolean flag=true;
		while(flag)
		{
			tempRandom=random.nextInt(u);
			if((!list.contains(tempRandom)))
			{
				list.add(tempRandom);
			}
			if(list.size()==v)
			{
				flag=false;
				break;
			}
		}
		return list;
	}
	/**
	 * trapdoorPlain���м���
	 * @param SK
	 * @param trapdoorPlain
	 * @return
	 */
	public static encryptedIndex encrypTropDoor(indexEncrypted SK,double []trapdoorPlain)
	{
		encryptedIndex res=new encryptedIndex();
		int []S=SK.getS();
		Matrix M1=SK.getM1();
		Matrix M2=SK.getM2();
		double []tempMD1=new double[trapdoorPlain.length];
		double []tempMD2=new double[trapdoorPlain.length];
		for(int i=0;i<S.length;i++)
		{
			//���S[i]==1,��ôtempMD1[i]=tempMD2[i]=plainIndex[i]
			if(S[i]==1)
			{
				tempMD1[i]=tempMD2[i]=trapdoorPlain[i];
			}
			//���S[i]==0,��ôtempMD1[i]+tempMD2[i]=plainIndex[i]
			else {
				double []sp=indexBuildTool.splitDouble(trapdoorPlain[i]);
				tempMD1[i]=sp[0];
				tempMD2[i]=sp[1];
			}
		}
		Matrix encryMatrix1=M1.inverse().times(new Matrix(tempMD1,1).transpose());
		Matrix encryMatrix2=M2.inverse().times(new Matrix(tempMD2,1).transpose());
		tempMD1=indexBuildTool.getArrayFromMatrix(encryMatrix1);
		tempMD2=indexBuildTool.getArrayFromMatrix(encryMatrix2);
		res.setMD1(tempMD1);
		res.setMD2(tempMD2);
		return res;
		
	}
}
